package com.sd365.permission.centre.service.rabbitmq.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.sd365.common.core.annotation.stuffer.IdGenerator;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.mq.ActionType;
import com.sd365.common.core.mq.MqDataSyncMsg;
import com.sd365.permission.centre.dao.mapper.UserMapper;
import com.sd365.permission.centre.dao.mapper.UserRoleMapper;
import com.sd365.permission.centre.entity.User;
import com.sd365.permission.centre.entity.UserRole;
import com.sd365.permission.centre.pojo.dto.easy2pass.ApplicationUserDTO;
import com.sd365.permission.centre.service.util.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;

@Slf4j
@ConditionalOnProperty(prefix = "MyMqConfig", name = "easypass", havingValue = "true")
@Component
public class Easy2passUserListener {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private IdGenerator idGenerator;

    public Easy2passUserListener() {
    }

    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = "easy2pass_user_centre"),
                    key = {"easy2pass_route_key"},
                    exchange = @Exchange(value = "easy2pass_exchange", type = "direct")
            )
    })
    public void easy2passUserReceiver(Channel channel, Message message) throws IOException {
        try {
            String body = new String(message.getBody(), "UTF-8");
            MqDataSyncMsg mqDataSyncMsg = JSON.parseObject(body, MqDataSyncMsg.class);
            List<Object> dataList = mqDataSyncMsg.getDataList();
            if (!CollectionUtils.isEmpty(dataList)) {
                log.info("body {}", body);
                List<ApplicationUserDTO> applicationUserDTOS = JSON.parseArray(JSON.toJSONString(dataList), ApplicationUserDTO.class);
                Boolean flag = this.processMqData(applicationUserDTOS, mqDataSyncMsg.getActionType());
                if (flag) {
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                }
            } else {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

    private Boolean processMqData(List<ApplicationUserDTO> dtos, ActionType actionType) {

        if (actionType.name().equals(ActionType.INSERT.name())) {
            return this.addUser(dtos);
        }
        if (actionType.name().equals(ActionType.UPDATE.name())) {
            return this.updateUser(dtos);
        }
        if (actionType.name().equals(ActionType.DELETE.name())) {
            return this.delUser(dtos);
        }
        return false;
    }


    private Boolean addUser(List<ApplicationUserDTO> applicationUserDTOS) {
        try {
            applicationUserDTOS.stream().forEach(item -> {
                User user = new User();
                user.setVersion(1L);
                user.setId(item.getId());
                user.setBirthday(item.getBirthday());
                user.setCode(item.getTel());
                user.setPassword(Md5Utils.digestHex(item.getPassword()));
                user.setName(item.getName());
                user.setTenantId(1337940702788714496L);
                Boolean flag = userMapper.insert(user) > 0;
                if (flag) {
                    UserRole userRole = new UserRole();
                    userRole.setId(idGenerator.snowflakeId());
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(1337645864428109824L);
                    userRole.setStatus((byte) 0);
                    userRole.setVersion(1L);
                    userRoleMapper.insert(userRole);
                }
            });
            return true;
        } catch (Exception e) {
            throw new BusinessException();
        }
    }

    /**
     * @param applicationUserDTOS
     * @return
     */
    private Boolean updateUser(List<ApplicationUserDTO> applicationUserDTOS) {
        return false;
    }

    /**
     * @param applicationUserDTOS
     * @return
     */
    private Boolean delUser(List<ApplicationUserDTO> applicationUserDTOS) {
        return false;
    }
}
